import { onload } from '../utils/index'
import tracker from '../utils/tracker'

export default function timming() {
  const observer = new PerformanceObserver(list => {
    for (const entry of list.getEntries()) {
      tracker.send({
        kind: 'experience', // 用户体验指标
        type: 'paint', // 统计每个阶段的时间
        paintType: entry.name, // 首次渲染类型
        startTime: entry.startTime, // 开始时间
        duration: entry.duration // 持续时间
      })
    }
  })
  observer.observe({
    entryTypes: ['paint']
  })

  onload(function () {
    setTimeout(() => {
      const {
        fetchStart,
        connectStart,
        connectEnd,
        requestStart,
        responseStart,
        responseEnd,
        domInteractive,
        domContentLoadedEventStart,
        domContentLoadedEventEnd,
        loadEventStart,
        loadEventEnd
      } = window.performance.getEntriesByType('navigation')[0]

      tracker.send({
        kind: 'experience', // 用户体验指标
        type: 'timing', // 统计每个阶段的时间
        connectTime: connectEnd - connectStart, // 连接时间
        ttfbTime: responseStart - requestStart, // 首字节到达时间
        responseTime: responseEnd - responseStart, // 响应读取时间
        parseDOMTime: loadEventEnd - loadEventStart, // DOM解析时间
        domContentLoadedTime:
          domContentLoadedEventEnd - domContentLoadedEventStart, // 内容加载时间
        timeToInteractive: domInteractive - fetchStart // 首次可交互时间
      })
    }, 3000)
  })
}
